const express = require("express");
const wsRouter = express.Router();
const expressWs = require("express-ws");
expressWs(wsRouter);

let wsList = [];
wsRouter.ws("/", function (ws) {
  let timer = null;
  timer = setInterval(() => {
    ws.send(
      JSON.stringify({
        type: "userVisits",
        msg: [
          { date: "2024-1-25", num: Math.round(Math.random() * 1000) },
          { date: "2024-1-24", num: Math.round(Math.random() * 1000) },
          { date: "2024-1-23", num: Math.round(Math.random() * 1000) },
          { date: "2024-1-22", num: Math.round(Math.random() * 1000) },
          { date: "2024-1-21", num: Math.round(Math.random() * 1000) },
        ],
      })
    );
  }, 3000);
  ws.on("message", function (msg) {
    // console.log("receive message: " + msg);
  });
  ws.on("close", function () {
    console.log("Connection closed");
    if (timer) {
      clearInterval(timer);
    }
  });
});

wsRouter.ws("/chat", function (ws) {
  ws.on("message", function (msg) {
    const msgData = JSON.parse(msg);
    if (msgData.type === "login") {
      ws.id = msgData.id;
      wsList.push(ws);
      return
    }
    if (msgData.type !== "heartbeat") {
      // 根据发送者的id，找到对应的ws，并发送消息
      wsList.forEach((e) => {
        if (e.id === msgData.to.id || e.id === msgData.from.id) {
          e.send(JSON.stringify(msgData));
        }
      });

      // 全员广播消息
      // wsList.forEach((e) => {
      //   e.send(JSON.stringify(msgData));
      // });
    }
  });
  ws.on("close", function () {
    console.log("Connection closed");
  });
});

module.exports = {
  wsRouter,
  wsList,
};
